﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing.Drawing2D;
using System.Drawing;

namespace Cosby.Models
{
    public class StripeSet
    {
        public LinearGradientMode Mode { get; set; }
        public List<Stripe> Stripes { get; set; }

        
        public StripeSet(string orientation, string widthcolors)
        {
            this.Mode = GetMode(orientation);

            if (string.IsNullOrWhiteSpace(widthcolors))
            {
                return;
            }

            //widthColors is an array of "width then colors"
            string[] widthOrcolorStrings = (widthcolors).Split("/".ToCharArray());
            this.Stripes = new List<Stripe>();
            for (int i = 0; i < widthOrcolorStrings.Length; i++)
            {
                var stripe = new Stripe() { Width = Convert.ToInt32(widthOrcolorStrings[i]), Color = GetColor(widthOrcolorStrings[i + 1]), ColorString = widthOrcolorStrings[i + 1] };
                this.Stripes.Add(stripe);
                i++;
            }
        }

        public static LinearGradientMode GetMode(string orientation)
        {
            LinearGradientMode mode = LinearGradientMode.Horizontal;
            if ((orientation ?? "H").StartsWith("V", StringComparison.InvariantCultureIgnoreCase))
            {
                mode = LinearGradientMode.Vertical;
            }
            return mode;
        }


        public static Color GetColor(string colorHexRgb)
        {
            if (string.IsNullOrWhiteSpace(colorHexRgb))
            {
                return Color.Black; //sensible default, as black wastes less power. 
            }

            if (colorHexRgb.Length == 3)
            {
                var color = Color.FromArgb(255, Convert.ToInt32(colorHexRgb.Substring(0, 1) + colorHexRgb.Substring(0, 1), 16),
                Convert.ToInt32(colorHexRgb.Substring(1, 1) + colorHexRgb.Substring(1, 1), 16),
                Convert.ToInt32(colorHexRgb.Substring(2, 1) + colorHexRgb.Substring(2, 1), 16));
                return color;
            }
            if (colorHexRgb.Length == 6)
            {
                var color = Color.FromArgb(255, Convert.ToInt32(colorHexRgb.Substring(0, 2), 16),
                Convert.ToInt32(colorHexRgb.Substring(2, 2), 16),
                Convert.ToInt32(colorHexRgb.Substring(4, 2), 16));
                return color;
            }

            throw new FormatException("Color was not well formatted {0}");
        }

    }
}